package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soft-release-mgr/cache"
	"soft-release-mgr/models"
	"time"
)

func AppAdd(c *gin.Context) {
	name := c.PostForm("name")
	address := c.PostForm("address")

	data := models.App{

		Name:    name,
		Address: address,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {

	var list []models.AppStyle
	/*
		SELECT
		  apps.`name` AS `Name`,
		  apps.address AS Address,
		  styles.style_name AS StyleName
		FROM
		  styles
		  LEFT JOIN apps ON styles.aid = apps.id
	*/
	models.DB.Select("apps.`name` AS `Name`",
		"apps.address AS Address",
		"styles.style_name AS StyleName",
	).Table("styles").
		Joins("LEFT JOIN apps ON styles.aid = apps.id").
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": list,
	})
}

func AppList(c *gin.Context) {

	var app []models.App
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": app,
	})
	return
}

func AppDetail(c *gin.Context) {

	id := c.Query("id")
	var app models.App
	redis_key := "detail_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Find(&app)
		jsonData, _ := json.Marshal(app)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &app)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": app,
	})
	return
}
